<template>
  <div class="layout">
    <div class="header">
      <div class="logo">{{ userInfo.storeName }}</div>
      <div class="userinfo">
        <span class="business-status">店铺状态：</span>
        <el-dropdown>
          <span class="business-name" :style="{ color: business.businessColor }">
            {{ business.businessName }}
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item v-for="item in otherBusinessArr" :key="item.status"
                @click="changeBusiness(item.status)">
                {{ item.name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        欢迎回来,
        <el-dropdown>
          <span class="name">{{ userInfo.contactName }}</span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="updatePwd">修改密码</el-dropdown-item>
              <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="body">
      <div class="left-sider">
        <div class="menu-list">
          <div :class="['menu-item', currentPmenu.menuUrl == item.menuUrl ? 'active' : '']"
            v-for="item in userInfo.menuList" @click="pMenuClickHandler(item)">
            <div class="iconfont"></div>
            <div class="menu-name">{{ item.menuName }}</div>
          </div>
        </div>
        <div class="menu-sub-list">
          <div @click="jump(sub)" :class="['sub-menu', currentSubMenu.menuUrl == sub.menuUrl ? 'active' : '']"
            v-for="sub in currentPmenu.children">
            {{ sub.menuName }}
          </div>
        </div>
      </div>
      <div class="main-content">
        <div class="tag-content">
          <el-tabs type="border-card" v-model="currentSubMenu.menuUrl" @tab-click="tabClick" @edit="editTab">
            <el-tab-pane :name="item.menuUrl" :label="item.menuName" :closable="tabList.length > 1"
              v-for="item in tabList"></el-tab-pane>
          </el-tabs>
        </div>
        <div class="body-content">
          <router-view></router-view>
        </div>
      </div>
    </div>
    <UpdatePwd ref="updatePwdRef"></UpdatePwd>
  </div>
</template>

<script setup>
import { color } from 'echarts';
import { ref, reactive, getCurrentInstance, nextTick, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import UpdatePwd from './UpdatePwd.vue';

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();

const api = {
  // 获取店铺状态
  getMerchantStatus: '/merchant/welcomePage/getMerchantStatus',
  // 修改店铺状态
  updateMerStatus: '/merchant/welcomePage/updateMerStatus',
  // 退出登录
  logout: '/merchant/logout',
}

// 用户信息
const userInfo = proxy.VueCookies.get("userInfo") || { menuList: [] }

// 营业状态
let businessStatus = ref()
const business = computed(() => {
  let businessName;
  let businessColor;
  switch (businessStatus.value) {
    case 0:
      businessName = '休息中';
      businessColor = '#B0B0B0';
      break;
    case 1:
      businessName = '营业中';
      businessColor = '#28A745';
      break;
    case 2:
      businessName = '自营中';
      businessColor = '#2196F3';
      break;
    default:
      businessName = '未开业';
      businessColor = '#FFA500';
  }
  return { businessName, businessColor };
})
// 营业状态
const businessArr = [{ name: '休息中', status: 0 }, { name: '营业中', status: 1 }, { name: '自营中', status: 2 },]

const otherBusinessArr = computed(() => {
  return businessArr.filter(item => item.status !== businessStatus.value)
})

// 首页加载店铺状态
const businessStatusFun = async () => {
  let result = await proxy.Request({
    url: api.getMerchantStatus,
  })
  businessStatus.value = result.data
}

// 修改店铺状态
const changeBusiness = async (value) => {
  const params = { status: value }
  let result = await proxy.Request({
    url: api.updateMerStatus,
    params: params
  })
  if (result.code == 200) {
    proxy.$message.success("修改成功");
    businessStatusFun();
  }
}

// 退出登录
const logout = async () => {
  proxy.Confirm('确定要退出登录吗？', async () => {
    let result = await proxy.Request({
      url: api.logout,
    })
    if (result.code === 200) {
      proxy.$message.success("已退出登录");
      proxy.VueCookies.remove('userInfo')
      proxy.VueCookies.remove('token')

      router.push('/login');
    }
  })
}

// 记录当前点击的子菜单
const currentSubMenu = ref({})

const updatePwdRef = ref({})

// 修改密码
const updatePwd = () => {
  updatePwdRef.value.show();
}

const menuMap = ref({})
const initMenuMap = () => {
  const menuList = userInfo.menuList
  // // 遍历所有一级菜单
  for (let p = 0; p < menuList.length; p++) {
    // 取出当前的一级菜单对象
    const pMenu = menuList[p];
    // 用菜单的路径 menuUrl 作为 key，把菜单对象存入 menuMap.value
    menuMap.value[pMenu.menuUrl] = pMenu
    // 如果该菜单有子菜单（children 不为空）
    if (pMenu.children && pMenu.children.length > 0) {
      // 遍历它的所有子菜单
      for (let s = 0; s < pMenu.children.length; s++) {
        // 取出当前子菜单对象
        const sub = pMenu.children[s]
        // 给子菜单加一个字段 parentPath，存父菜单路径
        sub["parentPath"] = pMenu.menuUrl
        // 用子菜单路径 menuUrl 作为 key，把子菜单对象存入 menuMap.value
        menuMap.value[sub.menuUrl] = sub
      }
    }
  }
}

// 当前选中的菜单
const currentPmenu = ref({ children: [] })
// 点击切换菜单
const pMenuClickHandler = (data) => {
  currentPmenu.value = data
  let firstsubMenu = data.children[0]
  jump(firstsubMenu)
}

const jump = (data) => {
  if (currentSubMenu.value.menuUrl == data.menuUrl) {
    return
  }
  currentSubMenu.value = data
  addTabHander(data)
  router.push(data.menuUrl)
}

// 页面加载选中的菜单
const menuSelect = (curPath, addTab) => {
  let curMenu = menuMap.value[curPath]
  if (curMenu == null) {
    return
  }
  currentPmenu.value = menuMap.value[curMenu.parentPath]
  currentSubMenu.value = curMenu
  if (addTab) {
    addTabHander(curMenu)
  }
}

// tab的操作
const tabList = ref([])

const addTabHander = (curMenu) => {
  // 查找与当前菜单选中的menuUrl 的 tab
  let currentTab = tabList.value.find((item) => {
    return item.menuUrl == currentSubMenu.value.menuUrl
  })

  // 如果不存在，就 push 一个新的 tab
  if (!currentTab) {
    tabList.value.push(curMenu)
  }
}

const tabClick = (e) => {
  // 从 tab 点击事件参数 e 里拿到 tab 对应的路由路径
  const path = e.props.name
  menuSelect(path)
  // 切换路由，显示对应页面内容
  router.push(path)
}

const editTab = (targetKey, action) => {
  // 如果 action 不是 "remove"，直接 return
  if (action !== "remove") {
    return
  }
  let curPath = currentSubMenu.value.menuUrl;
  let tabs = tabList.value
  // 如果 targetKey（要删除的 tab）正好是当前页面
  if (targetKey == curPath) {
    // 遍历 tab 列表，找到这个 tab 的位置
    tabs.forEach((tab, index) => {
      if (tab.menuUrl === targetKey) {
        // 优先选取右边的 tab（index + 1），如果没有，就选左边的（index - 1）
        let nextTab = tabs[index + 1] || tabs[index - 1];
        // 更新 curPath 为下一个应该显示的页面路径
        if (nextTab) {
          curPath = nextTab.menuUrl
        }
      }
    })
  }
  // 用 filter 去掉要删除的 tab
  tabList.value = tabs.filter((tab) => tab.menuUrl !== targetKey)
  // 如果 curPath 不等于当前页面路径，说明需要切换到新的 tab
  if (curPath != currentSubMenu.value.menuUrl) {
    // 跳转路由
    router.push(curPath)
    // 更新菜单选中状态
    menuSelect(curPath)
  }
}

onMounted(async () => {
  // 先获取店铺状态
  await businessStatusFun()

  // 初始化菜单映射表
  initMenuMap()

  // 等 DOM 渲染完成再处理下拉菜单相关（避免左上角问题）
  nextTick(() => {
    // menuSelect 同时选中首页菜单和初始化 tab
    menuSelect(route.path, true)
  })
})
</script>

<style lang="scss" scoped>
.layout {
  .header {
    border-bottom: 1px solid #ddd;
    height: 60px;
    padding-right: 24px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .logo {
      font-weight: bold;
      margin-left: 5px;
      font-size: 25px;
      color: #05a1f5;
    }

    .userinfo {
      margin-right: 20px;
      font-size: 14px;
      display: flex;
      align-items: center;
      cursor: default;

      .business-status {
        cursor: default;
        font-size: 12px;
      }

      .business-name {
        margin-right: 100px;
        cursor: pointer;
        font-size: 12px;
      }

      .name {
        font-size: 1;
        color: #409eff;
        cursor: pointer;
      }

      .user_type {
        margin-left: 5px;
      }

      .logout {
        margin-left: 15px;
      }
    }
  }

  .body {
    display: flex;

    .left-sider {
      width: 260px;
      display: flex;
      height: calc(100vh - 60px);
      border-right: 1px solid #f1f2f4;
      box-shadow: 0 3px 10px 0 rgba(14, 14, 14, 0.06);

      .menu-list {
        width: 70px;
        text-align: center;
        background: #1a1a1a;

        .menu-item {
          text-align: center;
          padding: 15px 0px;
          cursor: pointer;
          color: #fff;

          .iconfont {
            font-size: 20px;
          }

          .icon-app {
            font-size: 25px;
          }

          .menu-name {
            font-weight: bold;
          }

          &:hover {
            color: #06a7ff;
          }
        }

        .active {
          background: #06a7ff;

          &:hover {
            color: #fff;
          }
        }
      }

      .menu-sub-list {
        flex: 1;
        position: relative;
        padding: 5px 5px;

        .sub-menu {
          margin-top: 5px;
          cursor: pointer;
          padding: 10px 8px;
          border-radius: 5px;

          &:hover {
            color: #05a1f5;
          }
        }

        .active {
          background: #e8f4ff;
        }
      }
    }

    .main-content {
      width: 100%;

      .tag-content {
        :deep .el-tabs--border-card {
          border: none;
        }

        :deep .el-tabs__content {
          display: none;
        }
      }

      .body-content {
        padding: 10px;
      }
    }
  }
}
</style>